const {wechatLoginParams} = require('./configParams')
const axios = require('axios')

/**
 * 微信场景二维码api
 */
// 获取微信access_token
const getAccessToken = () => {
    return axios({
        method: 'get',
        url: wechatLoginParams.accessTokenPC
    })
}

// 获取拼接微信二维码url的ticket
const getTicket = (token) => {
    return axios({
        method: 'post',
        url: `https://api-v2.xdclass.net/cgi-bin/qrcode/create?access_token=${token}`,
        data: {
            expire_seconds: 60 * 2,
            action_name: "QR_SCENE",
            action_info: {
                "scene": {"scene_id": 123}
            }
        }
    })
}


/**
 * 微信app登录api
 */
// 获取app微信登录的accessToken
const getAccessTokenApp = (code) => {
    return axios({
        method: 'GET',
        url: 'https://api.weixin.qq.com/sns/oauth2/access_token',
        params: {
            code,
            appid: wechatLoginParams.appAppId,
            secret: wechatLoginParams.appAppSecret,
            grant_type: 'authorization_code'
        }
    })
}

// 获取app微信登录用户信息
const getUserInfoApp = (access_token, openid) => {
    return axios({
        method: 'GET',
        url: 'https://api.weixin.qq.com/sns/userinfo',
        params: {
            openid,
            access_token,
            lang: 'zh_CN'
        }
    })
}

const wechatLogin = {
    // 获取微信二维码url
    getOR: async () => {
        let token = (await getAccessToken()).data.access_token
        let ticket = (await getTicket(token)).data.ticket
        return {qrcodeUrl: `${wechatLoginParams.qrUrl}?ticket=${ticket}`, ticket: ticket}
    },
    // 获取用户信息
    getUserInfo: async (code) => {
        let data = (await getAccessTokenApp(code)).data
        let {access_token, openid} = data
        return (await getUserInfoApp(access_token, openid)).data
    },
    // 获取微信小程序OpenId
    getWeappOpenId: async (code) => {
        return axios({
            method: 'GET',
            url: 'https://api.weixin.qq.com/sns/jscode2session',
            params: {
                appid: wechatLoginParams.weappAppId,
                secret: wechatLoginParams.weappAppSecret,
                js_code: code,
                grant_type: 'authorization_code'
            }
        })
    }
}

module.exports = wechatLogin